package com.tpe.model.generic.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

import com.tpe.model.generic.repository.GenericCrudRepository;

@Stateless
public abstract class GenericCrudDao<T> implements GenericCrudRepository<T> {

	private final String PERSISTENCE_UNIT = "TpeDS";
	
	private Class<T> entity;
	
	@PersistenceContext(unitName=PERSISTENCE_UNIT)
	protected EntityManager em;
	
	public GenericCrudDao(Class<T> entity){
		this.entity = entity;
	}
	
	@Override
	public T criar(T entity) throws Exception{
		em.persist(entity);
		em.flush();
		return entity;
	}
	
	@Override
	public void deletar(T entity) throws Exception{
		entity = em.merge(entity);
		try{
			em.remove(entity);
			em.flush();
		} catch (Exception e){
			e.printStackTrace();
			throw new Exception("Erro ao tentar excluir registro.");
		}
	}
	
	@Override
	public T atualizar(T entity) throws Exception{
		try{
			entity = em.merge(entity);
			em.flush();
			return entity;
			
		} catch (Exception e){
			e.printStackTrace();
			throw new Exception("Erro ao tentar alterar registro.");
		}
	}
	
	@Override
	public T obterPorId(Long entityId) throws Exception{
		return em.find(entity, entityId);
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> obterTodos() throws Exception{
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(entity));
		return (List<T>) em.createQuery(cq).getResultList();
	}

}